package com.example.mobilesafe.service;

import android.app.ActivityManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;

import com.example.mobilesafe.activity.EnterPsdActivity;
import com.example.mobilesafe.dao.AppLockDao;

import java.util.List;

public class WatchDogService extends Service {

    private boolean isWatch;
    private AppLockDao mDao;
    private List<String> mPackageNameList;
    private InnerReceiver mInnerReceiver;
    private String mSkipPackageName;
    private MyContentObserver mContentObserver;

    @Override
    public void onCreate() {
        super.onCreate();
        // 维护一个看门狗的死循环，让其时刻监测现在开启的应用，是否为程序锁中要去拦截的应用
        mDao = AppLockDao.getInstance(this);
        isWatch = true;
        watch();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.SKIP");
        mInnerReceiver = new InnerReceiver();
        registerReceiver(mInnerReceiver,intentFilter);
        // 注册监听数据库变化的内容监听器
        mContentObserver = new MyContentObserver(new Handler());
        getContentResolver().registerContentObserver(Uri.parse("content://applock/change"),true,mContentObserver);
    }

    class MyContentObserver extends ContentObserver{

        public MyContentObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            // 一旦数据库发生改变（插入、删除数据）时调用的方法，需要重新获取包名所在集合的数据
            super.onChange(selfChange);
            new Thread(){
                @Override
                public void run() {
                    mPackageNameList = mDao.queryAll();
                }
            }.start();
        }
    }


    private class InnerReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 获取发送广播过程中传递过来的包名，跳过此包名的检测过程
            mSkipPackageName = intent.getStringExtra("packagename");
        }
    }

    /**
     * 开启死循环任务
     */
    private void watch() {
        // 1.开启一个死循环
        new Thread(){
            @Override
            public void run() {
                // 6.拿此包名在已加锁的包名集合中做比对，如果包含此包名，则需要弹出拦截界面
                mPackageNameList = mDao.queryAll();
                while (isWatch){
                    // 2.监测现在正在开启的应用，任务栈
                    // 3.获取Activity管理者对象
                    ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                    // 4.获取正在开启应用的任务栈的方法
                    List<ActivityManager.RunningTaskInfo> runningTasks = activityManager.getRunningTasks(1);
                    ActivityManager.RunningTaskInfo runningTaskInfo = runningTasks.get(0);
                    // 5.获取栈顶的Activity所在应用的包名
                    String packageName = runningTaskInfo.topActivity.getPackageName();
                    // 7.进行包名比对，如果包含此包名，则需要进行拦截
                    if (mPackageNameList.contains(packageName)) {
                        // 如果现在检测的程序，已经解锁了，则不需要去弹出拦截界面
                        if (!packageName.equals(mSkipPackageName)){
                            // 8.弹出拦截界面
                            Intent intent = new Intent(getApplicationContext(), EnterPsdActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.putExtra("packagename",packageName);
                            startActivity(intent);
                        }
                    }
                    // 9.因为死循环过多消耗性能，所以需要睡眠（时间片轮转）
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 将标识符置为false
        isWatch = false;
        // 注销广播接收者
        if (mInnerReceiver != null){
            unregisterReceiver(mInnerReceiver);
        }
        // 注销内容观察者
        if (mContentObserver != null){
            getContentResolver().unregisterContentObserver(mContentObserver);
        }
    }
}